<template>
  <div class="heritage-page">
    <div class="page-header">
      <h2>非遗推荐</h2>
      <p>探索中国传统非物质文化遗产的魅力</p>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="queryParams.heritageName"
        placeholder="搜索非遗名称"
        clearable
        class="search-input"
        @keyup.enter="handleQuery"
      >
        <template #append>
          <el-button @click="handleQuery">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd" class="add-button">
        <el-icon><Plus /></el-icon>添加推荐
      </el-button>
    </div>

    <!-- 卡片展示 -->
    <div v-loading="loading" class="heritage-cards">
      <el-empty v-if="heritageList.length === 0" description="暂无数据" />
      <el-row :gutter="24" v-else>
        <el-col :span="8" v-for="(item, index) in heritageList" :key="index" class="card-col">
          <el-card class="heritage-card" shadow="hover" @click="handleView(item)">
            <div class="card-content">
              <div class="card-header">
                <h3>{{ item.heritageName }}</h3>
                <el-tag size="small">{{ item.heritageType || item.level }}</el-tag>
              </div>
              <!-- 图片预览 -->
              <div class="card-image" v-if="item.images && item.images.length > 0">
                <el-image 
                  :src="formatImageUrl(item.images[0])"
                  fit="cover" 
                  class="carousel-image"
                  :preview-on-click="false"
                />
              </div>
              <div class="card-info">
                <p><el-icon><Location /></el-icon> {{ item.area || '未知地区' }}</p>
                <p class="description">{{ item.description || '暂无描述' }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[9, 18, 27, 36]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/查看对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="heritageFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="heritageName">
          <el-input v-model="form.heritageName" placeholder="请输入非遗名称" :disabled="dialog.readOnly" />
        </el-form-item>
        <el-form-item label="编号" prop="heritageCode">
          <el-input v-model="form.heritageCode" placeholder="请输入非遗编号" :disabled="dialog.readOnly" />
        </el-form-item>
        <el-form-item label="类型" prop="heritageType">
          <el-input v-model="form.heritageType" placeholder="请输入非遗类型" :disabled="dialog.readOnly" />
        </el-form-item>
        <el-form-item label="类别" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择类别" class="w-100" :disabled="dialog.readOnly">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地区" prop="area">
          <el-input v-model="form.area" placeholder="请输入所属地区" :disabled="dialog.readOnly" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别" class="w-100" :disabled="dialog.readOnly">
            <el-option label="国家级" value="国家级" />
            <el-option label="省级" value="省级" />
            <el-option label="市级" value="市级" />
            <el-option label="县级" value="县级" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入描述信息" 
            :disabled="dialog.readOnly" 
          />
        </el-form-item>
        <el-form-item label="历史背景" prop="history">
          <el-input 
            v-model="form.history" 
            type="textarea" 
            :rows="4"
            placeholder="请输入历史背景" 
            :disabled="dialog.readOnly" 
          />
        </el-form-item>
        <el-form-item label="传承情况" prop="inheritanceStatus">
          <el-input 
            v-model="form.inheritanceStatus" 
            type="textarea" 
            :rows="4"
            placeholder="请输入传承情况" 
            :disabled="dialog.readOnly" 
          />
        </el-form-item>
        
        <!-- 图片上传 -->
        <el-form-item label="上传图片" v-if="!dialog.readOnly">
          <el-upload
            action="/dev-api/user/heritage/upload/file"
            list-type="picture-card"
            :file-list="imageList"
            :on-preview="handleImagePreview"
            :on-remove="handleImageRemove"
            :on-success="handleImageSuccess"
            :headers="getHeaders()"
            accept="image/*"
            multiple
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png文件，且不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>
        
        <!-- 视频上传 -->
        <el-form-item label="上传视频" v-if="!dialog.readOnly">
          <el-upload
            action="/dev-api/user/heritage/upload/video"
            :file-list="videoList"
            :on-remove="handleVideoRemove"
            :on-success="handleVideoSuccess"
            :headers="getHeaders()"
            accept="video/*"
            multiple
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持MP4格式，单个文件不超过50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <!-- 图片显示 -->
        <el-form-item label="图片" v-if="dialog.readOnly && form.images && form.images.length > 0">
          <div class="image-preview">
            <el-image
              v-for="(img, imgIndex) in form.images"
              :key="imgIndex"
              :src="formatImageUrl(img)"
              fit="cover"
              class="preview-image"
              :preview-on-click="false"
            />
          </div>
        </el-form-item>
        
        <!-- 视频显示 -->
        <el-form-item label="视频" v-if="dialog.readOnly && form.videos && form.videos.length > 0">
          <div class="video-list">
            <div v-for="(video, videoIndex) in form.videos" :key="videoIndex" class="video-item">
              <video 
                :src="formatVideoUrl(video)" 
                controls 
                class="preview-video"
              ></video>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!dialog.readOnly">确 定</el-button>
          <el-button @click="cancel">{{ dialog.readOnly ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Plus, Location } from '@element-plus/icons-vue'
import { listHeritage, addHeritage, getHeritage, getHeritageTypes } from '@/api/system/heritage'
import { getToken } from '@/utils/auth'

const loading = ref(false)
const heritageList = ref([])
const total = ref(0)
const imageList = ref([])
const videoList = ref([])
const categoryOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 9,
  heritageName: undefined,
  heritageType: undefined
})

// 表单参数
const form = reactive({
  heritageName: undefined,
  heritageCode: undefined,
  heritageType: undefined,
  categoryId: undefined,
  area: undefined,
  level: undefined,
  description: undefined,
  history: undefined,
  inheritanceStatus: undefined,
  images: [],
  videos: []
})

// 表单校验规则
const rules = {
  heritageName: [{ required: true, message: '请输入非遗名称', trigger: 'blur' }],
  heritageCode: [{ required: true, message: '请输入非遗编号', trigger: 'blur' }],
  heritageType: [{ required: true, message: '请输入非遗类型', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择非遗类别', trigger: 'change' }],
  area: [{ required: true, message: '请输入所属地区', trigger: 'blur' }],
  level: [{ required: true, message: '请选择级别', trigger: 'change' }]
}

// 对话框
const dialog = reactive({
  visible: false,
  title: '',
  readOnly: false
})

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return '';
  
  // 检查是否为完整URL
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  
  // 检查是否已有/dev-api前缀
  if (url.startsWith('/dev-api/')) {
    return url;
  }
  
  // 检查是否为相对路径（以/开头）
  if (url.startsWith('/')) {
    return `/dev-api${url}`;
  }
  
  // 其他情况加上前缀
  return `/dev-api/${url}`;
}

// 格式化所有图片URL
const formatAllImages = (images) => {
  if (!images) return [];
  
  if (typeof images === 'string') {
    try {
      images = JSON.parse(images);
    } catch (e) {
      return [formatImageUrl(images)];
    }
  }
  
  if (!Array.isArray(images)) {
    return [formatImageUrl(images)];
  }
  
  return images.map(formatImageUrl).filter(url => url);
}

// 格式化视频URL
const formatVideoUrl = (url) => {
  if (!url) return '';
  
  // 检查是否为完整URL
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  
  // 检查是否已有/dev-api前缀
  if (url.startsWith('/dev-api/')) {
    return url;
  }
  
  // 检查是否为相对路径（以/开头）
  if (url.startsWith('/')) {
    return `/dev-api${url}`;
  }
  
  // 其他情况加上前缀
  return `/dev-api/${url}`;
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const response = await listHeritage(queryParams)
    heritageList.value = response.rows || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 处理新增
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增非遗推荐'
  dialog.readOnly = false
  
  // 重置表单数据
  Object.keys(form).forEach(key => form[key] = undefined)
  form.images = []
  form.videos = []
  imageList.value = []
  videoList.value = []
}

// 处理查看
const handleView = async (row) => {
  dialog.visible = true
  dialog.title = '查看非遗信息'
  dialog.readOnly = true
  
  try {
    loading.value = true
    // 获取详细信息
    const response = await getHeritage(row.heritageId)
    Object.assign(form, response.data || row)
    
    // 处理图片数据
    if (response.data?.images) {
      if (typeof response.data.images === 'string') {
        try {
          form.images = JSON.parse(response.data.images);
        } catch (e) {
          form.images = [response.data.images];
        }
      } else {
        form.images = response.data.images;
      }
    } else if (row.images) {
      form.images = row.images;
    } else {
      form.images = [];
    }
    
    // 处理视频数据
    if (response.data?.videos) {
      if (typeof response.data.videos === 'string') {
        try {
          form.videos = JSON.parse(response.data.videos);
        } catch (e) {
          form.videos = [response.data.videos];
        }
      } else {
        form.videos = response.data.videos;
      }
    } else if (row.videos) {
      form.videos = row.videos;
    } else {
      form.videos = [];
    }
  } catch (error) {
    console.error('获取详细信息失败:', error)
    Object.assign(form, row)
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  try {
    console.log('准备提交的原始表单数据:', JSON.stringify(form));
    
    // 创建一个克隆表单，用于提交
    const submitData = { ...form };
    
    // 确保数组不为null
    if (!submitData.images) submitData.images = [];
    if (!submitData.videos) submitData.videos = [];
    
    console.log('处理前的图片数组:', submitData.images);
    console.log('处理前的视频数组:', submitData.videos);
    
    // 将单个路径转换为包含单个元素的数组
    // StringArrayTypeHandler 需要字符串数组，即使只有一个元素
    if (typeof submitData.images === 'string') {
      submitData.images = [submitData.images];
    }
    
    if (typeof submitData.videos === 'string') {
      submitData.videos = [submitData.videos];
    }
    
    console.log('处理后的图片数据:', submitData.images);
    console.log('处理后的视频数据:', submitData.videos);
    console.log('提交的完整表单数据:', JSON.stringify(submitData));
    
    const response = await addHeritage(submitData);
    console.log('提交响应:', response);
    
    ElMessage.success('新增成功');
    dialog.visible = false;
    getList();
  } catch (error) {
    console.error('新增失败:', error);
    ElMessage.error('新增失败: ' + (error.message || '未知错误'));
  }
}

// 取消
const cancel = () => {
  dialog.visible = false
  Object.keys(form).forEach(key => form[key] = undefined)
  form.images = []
  form.videos = []
  imageList.value = []
  videoList.value = []
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 获取请求头
const getHeaders = () => {
  return { 
    Authorization: 'Bearer ' + getToken()
  }
}

// 获取类型列表
const getCategoryList = async () => {
  try {
    const response = await getHeritageTypes()
    categoryOptions.value = response.data || []
  } catch (error) {
    console.error('获取类型列表失败:', error)
  }
}

// 获取类别名称
const getCategoryName = (categoryId) => {
  const category = categoryOptions.value.find(item => item.categoryId === categoryId)
  return category ? category.categoryName : '未分类'
}

// 初始化
onMounted(() => {
  getList()
  getCategoryList()
})

// 图片上传相关方法
const handleImagePreview = (file) => {
  const imageUrl = file.url || (file.response?.msg ? formatImageUrl(file.response.msg) : '');
  window.open(imageUrl);
}

const handleImageRemove = (file, fileList) => {
  console.log('移除图片文件:', file);
  console.log('当前图片列表:', fileList);
  
  // 更新imageList引用
  imageList.value = fileList;
  
  // 从form.images中移除图片
  let fileUrl = '';
  if (file.response?.msg) {
    fileUrl = file.response.msg;
  } else if (file.url) {
    // 需要处理格式化后的URL, 去掉/dev-api前缀
    fileUrl = file.url.replace(/^\/dev-api/, '');
  }
  
  console.log('要移除的图片URL:', fileUrl);
  
  if (fileUrl && Array.isArray(form.images)) {
    const index = form.images.indexOf(fileUrl);
    if (index > -1) {
      form.images.splice(index, 1);
      console.log('移除图片后的图片数组:', form.images);
    } else {
      console.log('没有在images数组中找到要移除的图片URL');
    }
  }
}

const handleImageSuccess = (response, file) => {
  console.log('图片上传成功响应完整信息:', response, file);
  
  if (response.code === 200) {
    // 确保form.images是一个数组
    if (!Array.isArray(form.images)) {
      form.images = [];
    }
    
    // 从msg字段中获取URL (后端接口返回URL在msg字段中)
    const imageUrl = response.msg;
    if (imageUrl && !form.images.includes(imageUrl)) {
      form.images.push(imageUrl);
      console.log('更新后的图片数组:', form.images);
    }
    
    // 设置文件URL，确保el-upload组件正确显示预览
    file.url = formatImageUrl(imageUrl);
  } else {
    ElMessage.error('图片上传失败：' + response.msg);
  }
}

// 视频上传相关方法
const handleVideoRemove = (file, fileList) => {
  console.log('移除视频文件:', file);
  console.log('当前视频列表:', fileList);
  
  // 更新videoList引用
  videoList.value = fileList;
  
  // 从form.videos中移除视频
  let fileUrl = '';
  if (file.response?.msg) {
    fileUrl = file.response.msg;
  } else if (file.url) {
    // 需要处理格式化后的URL, 去掉/dev-api前缀
    fileUrl = file.url.replace(/^\/dev-api/, '');
  }
  
  console.log('要移除的视频URL:', fileUrl);
  
  if (fileUrl && Array.isArray(form.videos)) {
    const index = form.videos.indexOf(fileUrl);
    if (index > -1) {
      form.videos.splice(index, 1);
      console.log('移除视频后的视频数组:', form.videos);
    } else {
      console.log('没有在videos数组中找到要移除的视频URL');
    }
  }
}

const handleVideoSuccess = (response, file) => {
  console.log('视频上传成功响应完整信息:', response, file);
  
  if (response.code === 200) {
    // 确保form.videos是一个数组
    if (!Array.isArray(form.videos)) {
      form.videos = [];
    }
    
    // 从msg字段中获取URL (后端接口返回URL在msg字段中)
    const videoUrl = response.msg;
    if (videoUrl && !form.videos.includes(videoUrl)) {
      form.videos.push(videoUrl);
      console.log('更新后的视频数组:', form.videos);
    }
    
    // 设置文件URL，确保el-upload组件正确显示
    file.url = formatVideoUrl(videoUrl);
  } else {
    ElMessage.error('视频上传失败：' + response.msg);
  }
}
</script>

<style lang="scss" scoped>
.heritage-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .page-header {
    text-align: center;
    margin-bottom: 30px;

    h2 {
      font-size: 28px;
      color: #303133;
      margin-bottom: 10px;
    }

    p {
      font-size: 16px;
      color: #606266;
    }
  }

  .search-area {
    display: flex;
    margin-bottom: 20px;
    justify-content: space-between;

    .search-input {
      width: 300px;
    }
  }

  .heritage-cards {
    min-height: 300px;
    margin-bottom: 30px;

    .card-col {
      margin-bottom: 24px;
    }

    .heritage-card {
      cursor: pointer;
      transition: all 0.3s;
      height: 100%;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
      }

      .card-content {
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;

          h3 {
            margin: 0;
            font-size: 18px;
            color: #303133;
          }
        }
        
        .card-image {
          margin-bottom: 15px;
          height: 160px;
          overflow: hidden;
          border-radius: 8px;
          
          .el-image {
            width: 100%;
            height: 100%;
          }
        }

        .card-info {
          p {
            display: flex;
            align-items: center;
            gap: 5px;
            margin: 10px 0;
            color: #606266;
          }

          .description {
            color: #909399;
            margin-top: 10px;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 3;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.5;
            height: 4.5em;
          }
        }
      }
    }
  }

  .pagination-container {
    text-align: right;
    padding: 20px 0;
  }
}

.dialog-footer {
  text-align: right;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  
  .preview-image {
    width: 120px;
    height: 120px;
    border-radius: 4px;
  }
}

.video-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  
  .video-item {
    width: 100%;
    max-width: 320px;
    
    .preview-video {
      width: 100%;
      border-radius: 4px;
    }
  }
}

.detail-text {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
}
</style> 